package com.ruoyi.common.utils;

import com.qiniu.util.Hex;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

@Slf4j
public class AESUtil {

    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final String AES = "AES";


    public static String decrypt(String content, String aesKey) {
        if (StringUtils.isBlank(content) || StringUtils.isBlank(aesKey)) {
            log.error("[AESUtil.decrypt] encrypt or key is empty");
            return null;
        }

        try {
            byte[] raw = aesKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            return new String(cipher.doFinal(Hex.decodeHex(content.toCharArray())));
        } catch (Exception e) {
            log.error("AESUtil.decryptAES fail, error:[{}]", e.getMessage());
        }
        return null;
    }

    public static String encrypt(String content, String aesKey) {

        if (StringUtils.isBlank(content) || StringUtils.isBlank(aesKey)) {
            log.error("[AESUtil.encrypt] encrypt or key is empty");
            return null;
        }

        try {
            byte[] raw = aesKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return new String(Hex.encodeHex(cipher.doFinal(content.getBytes())));
        } catch (Exception e) {
            log.error("AESUtil.decryptAES fail, error:[{}]", e.getMessage());
            return null;
        }
    }

    /**
     * AES加密并转为二进制
     *
     * @param data   加密数据
     * @param hexKey 密钥
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, String hexKey) throws Exception {
        // 将十六进制密钥字符串转换为字节数组
        byte[] ivBytes = hexStringToByteArray(hexKey);
        // 初始化Cipher实例
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKeySpec keySpec = new SecretKeySpec(hexKey.getBytes(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        // 执行加密（返回原始二进制数据）
        return cipher.doFinal(data);
    }

    /**
     * AES加密并转为二进制
     *
     * @param encryptedData 解密数据
     * @param hexKey        密钥
     * @return
     * @throws Exception
     */
    public static String decrypt(byte[] encryptedData, String hexKey) throws Exception {
        // 将十六进制密钥字符串转换为字节数组
        byte[] ivBytes = hexStringToByteArray(hexKey);
        // 初始化Cipher实例
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKeySpec keySpec = new SecretKeySpec(hexKey.getBytes(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        // 执行解密
        return new String(cipher.doFinal(encryptedData));
    }

    /**
     * 十六进制字符串转字节数组
     *
     * @param s
     * @return
     */
    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}